#!/usr/bin/env python3
"""
简化启动脚本 - 用于测试和调试
"""

import sys
import os
import logging
import threading
import time
from pathlib import Path

# 添加项目根目录到Python路径
sys.path.insert(0, str(Path(__file__).parent))

def main():
    """简化主函数"""
    # 设置基本日志
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )
    
    logger = logging.getLogger(__name__)
    logger.info("🚀 启动简化版工业物联网系统")
    
    try:
        # 创建必要目录
        os.makedirs('logs', exist_ok=True)
        os.makedirs('data', exist_ok=True)
        
        # 初始化基本服务
        from services.storage import StorageService
        from services.alarm import AlarmService
        from services.scheduler import SchedulerService
        from core.engine import DataEngine
        from web.app import create_app
        
        logger.info("📦 初始化服务...")
        
        # 使用默认配置
        storage_service = StorageService({})
        alarm_service = AlarmService({})
        scheduler_service = SchedulerService()
        engine = DataEngine(
            storage_service=storage_service,
            alarm_service=alarm_service,
            max_workers=5
        )
        
        logger.info("✅ 基础服务初始化完成")
        
        # 加载设备配置
        logger.info("📋 加载设备配置...")
        load_devices_to_engine(engine)
        
        # 创建Web应用
        web_app = create_app(
            engine=engine,
            storage=storage_service,
            alarm=alarm_service,
            scheduler=scheduler_service,
            config={'debug': True}
        )
        
        # 启动数据采集引擎
        logger.info("🔧 启动数据采集引擎...")
        engine.start()
        
        # 启动调度服务
        logger.info("⏰ 启动调度服务...")
        scheduler_service.start()
        
        # 启动Web服务
        logger.info("🌐 启动Web服务...")
        logger.info("📍 访问地址: http://localhost:5000")
        logger.info("📱 设备配置: http://localhost:5000/device-config")
        logger.info("📊 监控仪表盘: http://localhost:5000/dashboard")
        
        web_app.run(
            host='0.0.0.0',
            port=5000,
            debug=False,
            use_reloader=False,
            threaded=True
        )
        
    except KeyboardInterrupt:
        logger.info("👋 系统正常退出")
    except Exception as e:
        logger.error(f"💥 系统异常: {e}")
        import traceback
        traceback.print_exc()

def load_devices_to_engine(engine):
    """加载设备配置到引擎"""
    try:
        from services.config_manager import ConfigManager
        
        config_manager = ConfigManager()
        devices_config = config_manager.load_devices()
        
        if not devices_config:
            logging.info("🤷 没有找到设备配置")
            return
        
        logging.info(f"🔍 发现 {len(devices_config)} 个设备配置")
        
        for device_config in devices_config:
            try:
                device_name = device_config.get('name')
                device_type = device_config.get('type')
                
                if not device_name or not device_type:
                    logging.warning(f"⚠️  设备配置缺少名称或类型: {device_config}")
                    continue
                
                if not device_config.get('enabled', True):
                    logging.info(f"💤 设备 {device_name} 被禁用，跳过")
                    continue
                
                # 创建设备驱动
                driver = create_device_driver(device_type, device_config)
                if driver:
                    engine.add_device(device_name, driver)
                    logging.info(f"✅ 设备 {device_name} ({device_type}) 加载成功")
                else:
                    logging.error(f"❌ 设备 {device_name} 驱动创建失败")
                
            except Exception as e:
                logging.error(f"❌ 设备 {device_config.get('name', 'Unknown')} 加载失败: {e}")
        
        # 显示加载统计
        total_devices = len(engine.devices)
        logging.info(f"📊 设备加载完成，共 {total_devices} 个设备")
        
    except Exception as e:
        logging.error(f"💥 加载设备配置失败: {e}")

def create_device_driver(device_type: str, device_config: dict):
    """创建设备驱动实例"""
    try:
        if device_type == 'modbus':
            from core.drivers.modbus import ModbusDriver
            return ModbusDriver(device_config)
        elif device_type == 's7':
            from core.drivers.s7 import S7Driver
            return S7Driver(device_config)
        elif device_type == 'opcua':
            from core.drivers.opcua import OpcuaDriver
            return OpcuaDriver(device_config)
        elif device_type == 'mqtt':
            from core.drivers.mqtt import MqttDriver
            return MqttDriver(device_config)
        else:
            logging.error(f"不支持的设备类型: {device_type}")
            return None
            
    except ImportError as e:
        logging.warning(f"⚠️  驱动模块导入失败: {e}")
        # 创建模拟驱动用于测试
        return create_mock_driver(device_config)
    except Exception as e:
        logging.error(f"创建驱动实例失败: {e}")
        return None

def create_mock_driver(device_config: dict):
    """创建模拟驱动用于测试"""
    try:
        from core.base_driver import BaseDriver
        
        class MockDriver(BaseDriver):
            """模拟驱动类"""
            def __init__(self, config):
                super().__init__(config)
                self.latest_data = {}
            
            def connect(self) -> bool:
                logging.info(f"🔌 模拟连接设备: {self.device_name}")
                self.connected = True
                return True
            
            def disconnect(self):
                logging.info(f"🔌 模拟断开设备: {self.device_name}")
                self.connected = False
            
            def read_all_tags(self):
                # 返回模拟数据
                from core.base_driver import TagValue
                from datetime import datetime
                
                tag_values = []
                for point in self.data_points:
                    tag_value = TagValue(
                        device_name=self.device_name,
                        tag_name=point.get('name', 'test_tag'),
                        value=25.5,  # 模拟温度值
                        timestamp=datetime.now(),
                        quality="GOOD"
                    )
                    tag_values.append(tag_value)
                
                return tag_values
        
        return MockDriver(device_config)
        
    except Exception as e:
        logging.error(f"创建模拟驱动失败: {e}")
        return None

if __name__ == "__main__":
    main() 